//
//  AppDelegate.m
//  zhiche--delivery
//
//  Created by LeeBruce on 16/5/6.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "AppDelegate.h"
#import "RootViewController.h"
#import "WelcomeViewController.h"
#import "LoginViewController.h"
#import <Pingpp.h>
#import "WKProgressHUD.h"
#import "UMMobClick/MobClick.h"
#import "Common.h"
#import "JPUSHService.h"
#import <AdSupport/AdSupport.h>
#import "SSKeychain.h"
#import <Masonry.h>
//分享
#import "UMSocialWechatHandler.h"
#import "UMSocialQQHandler.h"
#import "MyUncaughtExceptionHandler.h"

#import <UMSocialCore/UMSocialCore.h>


#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

#define UmengAppkey @"53290df956240b6b4a0084b3"


#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]

@interface AppDelegate ()<JPUSHRegisterDelegate>
{
    RootViewController *rootVC;
    Reachability *hostReach;//试试监听网络变化
    UIImageView * viewImage ;
}
@property (nonatomic,strong) WelcomeViewController *welcomeVC;
//@property (nonatomic,strong) RootViewController *rootVC;
@property (nonatomic,strong) LoginViewController *loginVC;

@property (nonatomic,copy) NSString *uuidString;

@end
@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = WhiteColor;
    
    [self createRooVC];
    [self chooseRootVC];
    [self.window makeKeyAndVisible];
    
    //获取错误日志
    [MyUncaughtExceptionHandler setDefaultHandler];

    
    
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
    
    //添加全局网络监听
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
    
    hostReach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    [hostReach startNotifier]; //开始监听,会启动一个run loop

//    [self updateInterfaceWithReachability:hostReach];
    
    //友盟统计
    UMConfigInstance.appKey = @"579ec58067e58ef2180011a7";
    UMConfigInstance.channelId = @"App Store";
//    UMConfigInstance.eSType = E_UM_GAME; //仅适用于游戏场景，应用统计不用设置
    [MobClick startWithConfigure:UMConfigInstance];//配置以上参数后调用此方法初始化SDK！
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *string = [userDefaults objectForKey:@"login_token"];
    
    if (string != nil) {
        [self checkUserToken];
    }
    
    [self JPUSHService:launchOptions];
    
    [[UMSocialManager defaultManager] setUmSocialAppkey:@"579ec58067e58ef2180011a7"];

    //设置微信的appKey和appSecret
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:@"wx5f0250600950a712" appSecret:@"a0cfe520d883ad8e6cab21d2710fe2c2" redirectURL:@"www.huiyunche.cn"];
    /*
     * 添加某一平台会加入平台下所有分享渠道，如微信：好友、朋友圈、收藏，QQ：QQ和QQ空间
     * 以下接口可移除相应平台类型的分享，如微信收藏，对应类型可在枚举中查找
     */
    //[[UMSocialManager defaultManager] removePlatformProviderWithPlatformTypes:@[@(UMSocialPlatformType_WechatFavorite)]];
    
    //设置分享到QQ互联的appID
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:@"101365467"/*设置QQ平台的appID*/  appSecret:@"46aca2a855cf137562a468a5d0c5ca8f" redirectURL:@"www.huiyunche.cn"];
    
    
    return YES;
}


-(void)JPUSHService:(NSDictionary*)launchOptions{
    
    //    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    //获取uuid
    [self sendUUID];
    
    
    
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
        JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
        entity.types = UNAuthorizationOptionAlert|UNAuthorizationOptionBadge|UNAuthorizationOptionSound;
        [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    }
    else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UNAuthorizationOptionBadge |
                                                          
                                                          UNAuthorizationOptionSound |
                                                          
                                                          UNAuthorizationOptionAlert)
         
                                              categories:nil];
        
    }
    
    else {
        
        //categories 必须为nil
        
        [JPUSHService registerForRemoteNotificationTypes:(UNAuthorizationOptionBadge |
                                                          
                                                          UNAuthorizationOptionSound |
                                                          
                                                          UNAuthorizationOptionAlert)
         
                                              categories:nil];
        
    }
    [JPUSHService setupWithOption:launchOptions appKey:appKey
                          channel:nil apsForProduction:nil];
    
    
    
    //2.1.9版本新增获取registration id block接口。
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            NSLog(@"registrationID获取成功：%@",registrationID);
            
            
            NSString *strUrl = [self.uuidString stringByReplacingOccurrencesOfString:@"-" withString:@""];
            NSLog(@"uuidString:%@",strUrl);
            
            //            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            //            [userDefaults setObject:registrationID forKey:@"registrationID"];
            //
            
            [JPUSHService setAlias:strUrl  callbackSelector:nil object:nil];
        }//7C3129208DB44A399BDCAEF0729AA780
        else{
            NSLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
    
}

- (void)networkDidLogin:(NSNotification *)notification {
    
    
    if ([JPUSHService registrationID]) {
        NSLog(@"get RegistrationID:%@",[JPUSHService registrationID]);//获取registrationID
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:[JPUSHService registrationID] forKey:@"pushid"];
    }
}


//监听到网络状态改变
- (void) reachabilityChanged: (NSNotification* )note

{
    Reachability* curReach = [note object];
    NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
    [self updateInterfaceWithReachability: curReach];
    
}

//处理连接改变后的情况
- (void) updateInterfaceWithReachability: (Reachability*) curReach

{
    //对连接改变做出响应的处理动作。
    NetworkStatus status = [curReach currentReachabilityStatus];
    
    if(status == NotReachable)
  {
        [WKProgressHUD popMessage:@"网络异常，请检查网络配置" inView:self.window duration:1.5 animated:YES];
    }
}

-(WelcomeViewController *)welcomeVC
{
    if (!_welcomeVC) {
        _welcomeVC = [[WelcomeViewController alloc]init];
        __weak typeof(self) weakSelf = self;
        
        _welcomeVC.callBack = ^(){
            [weakSelf chooseRootVC];
        };
    }
    return _welcomeVC;
}
//zhiche--delivery-CeShi-Info    zhiche--delivery-KaiFa-Info
-(void)createRooVC
{
    rootVC = [RootViewController defaultsTabBar];;
}

-(void)chooseRootVC
{
    
    
    self.window.rootViewController = rootVC;

//    BOOL flag = [[NSUserDefaults standardUserDefaults]boolForKey:@"firstIn"];
//    
//    if (flag == YES) {
//        self.window.rootViewController = rootVC;
//    } else {
//        self.window.rootViewController = self.welcomeVC;
//    }
}

//-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
//{
//   return  [UMSocialSnsService handleOpenURL:url   wxApiDelegate:nil];
//}



-(void)application:(UIApplication *)application didReceiveLocalNotification:(nonnull UILocalNotification *)notification{
    
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = WhiteColor;
    [JPUSHService showLocalNotificationAtFront:notification identifierKey:nil];
    [self createRooVC];
    [self chooseRootVC];
    [self.window makeKeyAndVisible];
}

//- (BOOL)application:(UIApplication *)app
//            openURL:(NSURL *)url
//            options:(NSDictionary *)options {
//    BOOL canHandleURL = [Pingpp handleOpenURL:url withCompletion:nil];
//    return canHandleURL;
//}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970] * 1000;
    NSString *timeString = [NSString stringWithFormat:@"%.0f", a];
    NSDictionary *dic = @{@"time":timeString};
    
    [[NSNotificationCenter defaultCenter]postNotificationName:@"background" object:nil userInfo:dic];
    viewImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, Main_Width, Main_height)];
    viewImage.image = [UIImage imageNamed:@"6"];
    [self.window addSubview:viewImage];
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    
    NSString * stringVS = [NSString stringWithFormat:@"V%@",app_Version];
    
    UILabel * label = [[UILabel alloc]init];
    label.text = stringVS;
    label.textColor = YellowColor;
    label.font = Font(FontOfSize10);
    [viewImage addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(viewImage.mas_centerX);
        make.bottom.mas_equalTo(viewImage.mas_bottom).with.offset(-10*kHeight);
        make.size.mas_equalTo(CGSizeMake(30*kWidth, 17.5*kHeight));
    }];

    
    
    //极光推送
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];

}
- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970] * 1000;
    NSString *timeString = [NSString stringWithFormat:@"%.0f", a];
    NSDictionary *dic = @{@"time":timeString};
    
//    //延迟执行
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        
//        
//    });

    [[NSNotificationCenter defaultCenter]postNotificationName:@"foreground" object:nil userInfo:dic];
    [self performSelector:@selector(delayMethod) withObject:nil afterDelay:1];
    

    
    //极光
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}

-(void)delayMethod{
    
    [viewImage removeFromSuperview];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *string = [userDefaults objectForKey:@"login_token"];
    
    if (string != nil) {
        
        [self checkUserToken];
        
    }
    
    
//    [UMSocialSnsService  applicationDidBecomeActive];

}


-(void)checkUserToken
{
    [Common requestWithUrlString:token_check contentType:application_json finished:^(id responseObj) {
        
          
        if ([responseObj[@"success"] boolValue]) {
            
        } else {
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            [userDefaults setObject:nil forKey:@"login"];
            [userDefaults setObject:nil forKey:@"login_token"];
        }
        
    } failed:^(NSString *errorMsg) {
        
    }];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [NSString stringWithFormat:@"%@", deviceToken];
//    NSLog(@"Device Token%@", [NSString stringWithFormat:@"Device Token: %@", deviceToken]);
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
- (void)application:(UIApplication *)application
didRegisterUserNotificationSettings:
(UIUserNotificationSettings *)notificationSettings {
}

// Called when your app has been activated by the user selecting an action from
// a local notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application
handleActionWithIdentifier:(NSString *)identifier
forLocalNotification:(UILocalNotification *)notification
  completionHandler:(void (^)())completionHandler {
}

// Called when your app has been activated by the user selecting an action from
// a remote notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application
handleActionWithIdentifier:(NSString *)identifier
forRemoteNotification:(NSDictionary *)userInfo
  completionHandler:(void (^)())completionHandler {
}
#endif

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
    [JPUSHService handleRemoteNotification:userInfo];
    NSLog(@"收到通知:%@", [self logDic:userInfo]);
}

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:
(void (^)(UIBackgroundFetchResult))completionHandler {
    [JPUSHService handleRemoteNotification:userInfo];
    NSLog(@"收到通知:%@", [self logDic:userInfo]);
    
    completionHandler(UIBackgroundFetchResultNewData);
}
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#pragma mark- JPUSHRegisterDelegate
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    NSDictionary * userInfo = notification.request.content.userInfo;
    
    UNNotificationRequest *request = notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        NSLog(@"iOS10 前台收到远程通知:%@", [self logDic:userInfo]);
        
        //        [rootViewController addNotificationCount];
        
    }
    else {
        // 判断为本地通知
        NSLog(@"iOS10 前台收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
}

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    UNNotificationRequest *request = response.notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        NSLog(@"iOS10 收到远程通知:%@", [self logDic:userInfo]);
        //        [rootViewController addNotificationCount];
        
        //tag:0   司机认证  1 待接单 2 执行中
        
        
        NSString * strTag = [NSString stringWithFormat:@"%@",userInfo[@"tag"]];
        
        if ([strTag isEqualToString:@"0"]) {
            

        }else if ([strTag isEqualToString:@"1"]){
            
            
            
          
        }else{

        }
        
    }
    else {
        // 判断为本地通知
        NSLog(@"iOS10 收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    
    completionHandler();  // 系统要求执行这个方法
}
#endif


- (NSString *)logDic:(NSDictionary *)dic {
    if (![dic count]) {
        return nil;
    }
    NSString *tempStr1 =
    [[dic description] stringByReplacingOccurrencesOfString:@"\\u"
                                                 withString:@"\\U"];
    NSString *tempStr2 =
    [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 =
    [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString *str =
    [NSPropertyListSerialization propertyListFromData:tempData
                                     mutabilityOption:NSPropertyListImmutable
                                               format:NULL
                                     errorDescription:NULL];
    return str;
}

-(void)sendUUID{
    //    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    CFUUIDRef uuid = CFUUIDCreate(NULL);
    assert(uuid != NULL);
    CFStringRef uuidStr = CFUUIDCreateString(NULL, uuid);
    if (![SSKeychain passwordForService:@"com.sandwish.eduOnline" account:@"user"]) {//查看本地是否存储指定 serviceName 和 account 的密码
        
        [SSKeychain setPassword: [NSString stringWithFormat:@"%@", uuidStr]
                     forService:@"com.sandwish.eduOnline"account:@"user"];
        //从钥匙串读取UUID：
        NSString *retrieveuuid = [SSKeychain passwordForService:@"com.sandwish.eduOnline"account:@"user" ];
        //       NSLog(@"SSKeychain存储显示 :第一次安装过:%@", retrieveuuid);
        
        
        self.uuidString = [NSString stringWithFormat:@"%@",retrieveuuid];
        
    }else{
        
        //曾经安装过 则直接能打印出密码信息(即使删除了程序 再次安装也会打印密码信息) 区别于 NSUSerDefault
        
        
        //从钥匙串读取UUID：
        NSString *retrieveuuid = [SSKeychain passwordForService:@"com.sandwish.eduOnline"account:@"user"];
        NSLog(@"SSKeychain存储显示 :已安装过:%@", retrieveuuid);
        
        self.uuidString = [NSString stringWithFormat:@"%@",retrieveuuid];
        
    }
}
//#define __IPHONE_10_0    100000
#if __IPHONE_OS_VERSION_MAX_ALLOWED > 100000
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
{
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    return result;
}

#endif

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    return result;
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    return result;
}



@end
